package capricornus.components.utils.displayneartips
{
	import capricornus.components.tilelist.SimpleList;
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	internal class DisplayNearList extends Sprite
	{
		private var _list:SimpleList;
		
		private var _direct:int;
		
		private var _num:int = 0;
		
		private var _maxLen:int = 9999;
		
		public function DisplayNearList()
		{
			super();
			init();
		}
		
		private function init():void
		{
			_list = new SimpleList();
			addChild( _list );
			this.mouseEnabled = false;
		}
		
		public function set maxLen( value:int ):void
		{
			_maxLen = value;
			
			handleLen();
		}
		
		private function handleLen():void
		{
			if( _maxLen==0 ) return;
			var i:int = 1;
			while( _list.length > _maxLen )
			{
				if( _direct==DisplayNearTipsDirection.UP )
				{
					DisplayNearItem(_list.getItemAt(0)).destroy();
				}
				else
				{
					DisplayNearItem(_list.getItemAt(_list.length-i)).destroy();
					i++;
				}
			}
		}
		
		public function addItem( di:DisplayNearItem, direct:int ):void
		{
			_direct = direct;
			if( direct==DisplayNearTipsDirection.UP )
			{
				_list.addItem( di );
			}
			else
			{
				_list.addItemAt( di, 0 );
			}
			_list.refresh();
			
			_num++;
			
			di.addEventListener( DisplayNearEvent.HIDE, onDiRemoved, false, 0, true );
			
			handleLen();
			
			refresh();
		}
		
		public function refresh():void
		{
			if( _direct==DisplayNearTipsDirection.UP )
			{
				_list.y = -int(_list.height);
			}
			else
			{
				_list.y = 0;
			}
		}
		
		private function onDiRemoved( e:Event ):void
		{
			var di:DisplayNearItem = e.currentTarget as DisplayNearItem;
			di.removeEventListener( DisplayNearEvent.HIDE, onDiRemoved );
			_list.removeItem( di );
			_num--;
			
			refresh();
			
			if( _num <= 0 )
			{
				_list.removeAll();
				if( parent != null )
				{
					parent.removeChild( this );
				}
				dispatchEvent( e );
			}
		}
	}
}





